package com.doge.walknovel.business.novel.widgets

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.drawable.toBitmap
import com.doge.wnpro.R
import com.doge.walknovel.utils.dp
import com.doge.walknovel.utils.getDrawable
import com.doge.walknovel.utils.isMainThread
import kotlin.math.max
import kotlin.math.min

class ScoreView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : View(context, attrs) {
    private val paint by lazy { Paint() }
    private val light by lazy { getDrawable(R.mipmap.star_light)!!.toBitmap() }
    private val grey by lazy { getDrawable(R.mipmap.star_grey)!!.toBitmap() }
    private val maxScore = 5
    private var score: Float = 0f

    fun setScore(value: Float) {
        require(isMainThread())
        score = max(0f, min(maxScore.toFloat(), value / 2))
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        setMeasuredDimension((12 * maxScore + 3 * (maxScore - 1)).dp, 12.dp)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas ?: return

        val percent = score / maxScore
        val side = percent * width
        canvas.save()
        canvas.clipRect(0f, 0f, side, height.toFloat())
        repeat(maxScore) {
            canvas.drawBitmap(light, 15.dp * it * 1f, 0f, paint)
        }
        canvas.restore()
        canvas.save()
        canvas.clipRect(side, 0f, width.toFloat(), height.toFloat())
        repeat(maxScore) {
            canvas.drawBitmap(grey, 15.dp * it * 1f, 0f, paint)
        }
        canvas.restore()
    }
}